# -*-coding: utf-8 -*-

import VBAPI
from win32com import client
from mainwindow import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtCore import pyqtSlot, Qt
import sys
import traceback


class mainwin(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(mainwin, self).__init__(parent)
        self.setupUi(self)
        self.actionconnect.triggered.connect(self.connect)

        self.Asyncconnection = None

    def closeEvent(self, event):
        self.disconnect()
        event.accept()

    def connect(self):
        cAC = client.Dispatch(VBAPI.CCpfcAsyncConnection)
        try:
            self.Asyncconnect = cAC.Connect(None, None, None, None)
            session = self.Asyncconnect.Session
            models = session.ListModelsByType(getattr(VBAPI.constants, 'EpfcMDL_DRAWING'))
            for i in range(models.Count):
                self.tbmessage.append(str(models.Item(i).FileName))
            # model = session.GetActiveModel()
            # window = session.GetModelWindow(model)
            # self.tbmessage.append(str(window.GetId()))
            self.statusbar.showMessage('连接成功！')
        except Exception as e:
            print('connect fail')
            print(traceback.print_exc())

    def disconnect(self):
        try:
            if self.Asyncconnect.IsRunning():
                self.Asyncconnect.Disconnect(None)
        except Exception as e:
            print('disconnect fail!')
            print(traceback.print_exc())

    @pyqtSlot()
    def on_pbaddcenter_clicked(self):
        self.select()

    def select(self):
        self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.show()
        session = self.Asyncconnect.Session
        selectoptions = client.Dispatch(VBAPI.CCpfcSelectionOptions).Create('edge')
        selectoptions.MaxNumSels = 1
        try:
            selected = session.Select(selectoptions, None)  #IpfcSelections
            if selected is not None:
                selectedge = selected.Item(0).SelItem #IpfcModelItem
                descriptor = selectedge.GetCurveDescriptor()
                geotype = descriptor.GetCurveType()
                if geotype == 4:
                    loc = []
                    for i in range(3):
                        loc.append(descriptor.Center.Item(i))
                    self.tbmessage.append('center:' + str(loc))
                    self.tbmessage.append('radius:' + str(descriptor.Radius))
                    end1 = descriptor.Center
                    end2 = session.UIGetNextMousePick(getattr(VBAPI.constants, 'EpfcMOUSE_BTN_LEFT')).Position
                    end1.Set(2, end2.Item(2))
                    end2xr = end2
                    end2xr.Set(1, end2.Item(1))
                    linedescriptor = client.Dispatch(VBAPI.CCpfcLineDescriptor).Create(end1, end2xr)
                    lineinstruction = client.Dispatch(VBAPI.CCpfcDetailEntityInstructions).Create(linedescriptor)
                    session = self.Asyncconnect.Session
                    models = session.ListModelsByType(getattr(VBAPI.constants, 'EpfcMDL_DRAWING'))
                    model = models.Item(0)
                    if model is None:
                        self.tbmessage.append('fail')
                    else:
                        model.CreateDetailItem(lineinstruction)
        except Exception as e:
            print(traceback.print_exc())
            self.tbmessage.append(e)
        self.setWindowFlags(Qt.Widget)
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = mainwin()
    win.show()
    sys.exit(app.exec_())

